#!/usr/bin/python -S
"""
p4_test.py: Tests for p4 JSON Patterns
"""

__author__ = 'Andy Chu'


import os
from pprint import pprint
import sys

from pan.core import cmdapp
from pan.core import params
from pan.core import json
from pan.core import util
from pan.test import testy

if __name__ == '__main__':
  # for jsonpattern package
  sys.path.insert(
      0, os.path.join(os.path.dirname(__file__), '..', 'python'))
  # Root of the project
  sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from tests import test_main

import jsonpattern


def Eval(value, stack):
  try:
    l2 = stack.pop()
    l1 = stack.pop()
  except IndexError:
    return None  # Stop the match

  token = value
  if token == '+': res = l1 + l2
  elif token == '-': res = l1 - l2
  elif token == '*': res = l1 * l2
  elif token == '/': res = l1 / l2

  stack.append(res)
  return value  # Indicate success


class RpnTest(testy.Test):

  LABELS = ['multilanguage']

  def testRpn(self):
    library = {}
    actions = {
        'eval!': Eval,
        }

    def Add(name, pattern, desc=None):
      library[name] = jsonpattern.Pattern(
          pattern, patterns=library, actions=actions, name=name, desc=desc)

    p = r"""
         | repeated tokens
         |   choice
        P|     { [+\-/*] | eval! }
         |   or
        P|     { \d(\.\d+)? | float | push! }
         |   end
        P|   \s*
         | end
        """
    Add('expr', p)

    expr = library['expr']

    print expr.AsTree()

    stack = []
    result = expr.match('12+', workspace=stack)
    print result.data
    print stack[0]

    stack = []
    result = expr.match('1 2 -', workspace=stack)
    print result.data
    print stack[0]

    stack = []
    result = expr.match('1 2 + 4.5 *', workspace=stack)
    print result.data
    print stack[0]

    stack = []
    result = expr.match('1 2 + 4.5 * *', workspace=stack)
    print result.data
    # Verify that we only matched the good data, not the last *
    self.verify.Equal(result.data, {'tokens': [1.0, 2.0, '+', 4.5, '*']})


if __name__ == '__main__':
  test_main.main(__import__(__name__), sys.argv[1:])
